import {Mesh} from "three";
import {PointGroup} from "./PointGroup.ts";
import {releaseMesh} from "../../../framework/util.ts";

export class PointLineContainerMesh extends PointGroup{

    circles: Mesh[]
    maxLines: number
    curLine: number

    onFull?: (m: Mesh[])=>void

    constructor(width: number, height: number) {
        super(width, height)
        this.width = width
        this.height = height
        this.curLine = 0
        this.maxLines = this.height

        this.circles = []
    }

    addCircle(mesh: Mesh) {
        mesh.position.setY(-this.height/2)
        this.add(mesh)
        this.circles.push(mesh)
    }

    addCircleLine(items: Mesh[]) {

        // console.log('添加一行buffer')
        this.moveUp()

        for (let i = 0; i < items.length; i++) {
            let m = items[i]
            this.addCircle(m)
        }
        this.curLine++
        if (this.isFull()) {
            // console.log('point buffer full')
            this.curLine = 0
            let list = this.circles
            this.circles = []
            this.removeMesh(list)
            if (!this.onFull) {
                this.releaseMesh()
            } else {
                this.onFull(list)
            }
        }
    }

    moveUp() {
        for (let i = 0; i < this.circles.length; i++) {
            let m = this.circles[i]
            m.position.setY(m.position.y+1)
        }
    }
    removeMesh(list: Mesh[]) {
        for (let i = 0; i < list.length; i++) {
            let line = list[i]
            this.remove(line)
        }
    }

    releaseMesh() {
        // console.log('point buffer销毁', '圆形mesh')
        let length = this.circles.length
        for (let i = 0; i < length; i++) {

            let m = this.circles.shift()
            if (!m) {
                continue
            }
            releaseMesh(m)
        }
    }

    isFull(): boolean {
        return this.curLine >= this.maxLines
    }
}